const express = require('express');
const router = express.Router();
const db = require('../db/mysqlConfig');

// 获取用户历史订单
router.get('/api/order/history', (req, res) => {
    const { user_id } = req.query;

    if (!user_id) {
        return res.status(400).json({ code: '1', data: { message: '缺少 user_id' } });
    }

    const sql = `
        SELECT 
            o.order_id,
            o.billiard_room_id,
            o.room_id,
            o.start_time,
            o.end_time,
            o.total_time,
            o.amount,
            o.created_time,
            o.status,
            o.payment_type,
            br.room_name AS shop_name,
            rt.table_number,
            r.rating,
            r.comment,
            r.images,
            r.created_at AS review_created_at
        FROM orders o
        LEFT JOIN billiard_rooms br ON o.billiard_room_id = br.room_id
        LEFT JOIN room_table rt ON o.room_id = rt.table_id
        LEFT JOIN reviews r ON o.order_id = r.order_id
        WHERE o.user_id = ? AND o.status IN ('reviewed', 'refunded', 'completed')
        ORDER BY o.created_time DESC;
    `;

    db.query(sql, [user_id], (error, results) => {
        if (error) {
            return res.status(500).json({ code: '1', data: { message: '查询失败', error } });
        }

        // 格式化数据
        const formattedResults = results.map(row => ({
            order_id: row.order_id,
            billiard_room_id: row.billiard_room_id,
            room_id: row.room_id,
            start_time: row.start_time,
            end_time: row.end_time,
            total_time: row.total_time,
            amount: row.amount.toFixed(2),
            created_time: row.created_time,
            status: row.status,
            payment_type: row.payment_type,
            shop_name: row.shop_name,
            table_number: row.table_number,
            ...(row.rating ? {
                review: {
                    rating: row.rating,
                    comment: row.comment,
                    images: row.images ? JSON.parse(row.images) : [],
                    created_at: row.review_created_at
                }
            } : {})
        }));

        res.json({ code: '0', data: formattedResults });
    });
});

module.exports = router;
